/**
 * @author：anlzou
 * @Date：Created in7:14 2021/4/13
 * @Github：https://github.com/anlzou
 * @Description：
 */
package com.anlzou.logic;

import com.anlzou.utlis.CreateDir;

import java.io.*;

public class Serializable {

    /**序列化*/
    public Boolean serialize(Object e, String filePathName){
        if (filePathName.lastIndexOf("/") != -1){//有文件路径
            //判断文件夹是否存在，不存在则创建
            String dirName = filePathName.substring(0,filePathName.lastIndexOf("/"));
            new CreateDir(dirName);
        }

        try {
            //FileOutputStream不支持序列化方法
            FileOutputStream fileOut = new FileOutputStream(filePathName);
            //ObjectOutputStream支持序列化
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(e);

            out.close();
            fileOut.close();
            return true;
        }catch (IOException i){
            i.printStackTrace();
        }
        return false;
    }


    /**反序列化*/
    public Object deserialize(String filePathName){
        Object e = null;

        try {
            FileInputStream fileIn = new FileInputStream(filePathName);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = in.readObject();

            in.close();
            fileIn.close();
            return e;
        }catch(IOException i) {
            i.printStackTrace();
        }catch(ClassNotFoundException c) {
            System.out.println(filePathName + " not found");
            c.printStackTrace();
        }
        return null;
    }

}
